﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using Threads;

namespace AutoBuildVersion.Helper
{
    public class MsBuilder
    {
        private static readonly MainWindow View = MainWindow.GetWindow();

        private static readonly List<string> errorlist = new List<string>();

        public static void ReBulid(string filename, string rootpath)
        {
            View.rtbMainDescription.Clear();
            errorlist.Clear();
            View.rtbMainDescription.AppendText("======================================================" + "\r\n");
            View.rtbMainDescription.AppendText("开始重编译 ..." + "\r\n");
            View.rtbMainDescription.AppendText("======================================================" + "\r\n");


            var cmd = string.Format(@"@ECHO OFF
           
           SET __MSBUILD_EXE__=%windir%\microsoft.net\framework64\v4.0.30319\msbuild.exe
           @echo on
           %__MSBUILD_EXE__%  {0} /t:Rebuild /p:Configuration=release;Platform=x86
           @echo off
           ", filename);


            var runer = new CmdRuner(cmd);

            runer.RunCmd(e => UIThread.Invoke(() =>
            {
                if (e.Data.IsNotNullOrEmpty())
                {
                    View.rtbMainDescription.AppendText(e.Data + "\r\n");
                    if (e.Data.Contains(": error ")) //如果编译出错记录错误
                    {
                        errorlist.Add(e.Data);
                    }
                }
            }), null, e =>
            {
                if (errorlist.Any())
                {
                    var errbuilder = new StringBuilder();
                    errbuilder.AppendLine("-->" + "重编译出现错误，一下为错误：");
                    foreach (var err in errorlist)
                    {
                        errbuilder.AppendLine(err);
                    }

                    UIThread.Invoke(() => View.rtbStepDescription.AppendText(errbuilder.ToString()));
                }
                else
                {
                    UIThread.Invoke(() => View.rtbStepDescription.AppendText("-->" + "重编译成功 √" + "\r\n"));
                }
            }
                );
        }
    }
}